@inherits RadzenComponent
@using Microsoft.JSInterop
<div @ref=@Element @onmousedown:preventDefault=@PreventDefault @attributes=@Attributes style=@Style id=@GetId()>
    @if (open || !Lazy)
    {
        @ChildContent
    }
</div>
@code {
    bool open;

    [Parameter]
    public bool Lazy { get; set; }

    [Parameter]
    public RenderFragment ChildContent { get; set; }

    [Parameter]
    public bool PreventDefault { get; set; }

    [Parameter]
    public EventCallback Open { get; set; }

    [Parameter]
    public EventCallback Close { get; set; }

    public async Task ToggleAsync(ElementReference target)
    {
        open = !open;
        this.target = target;

        if (open)
        {
            await Open.InvokeAsync(null);
            await JSRuntime.InvokeVoidAsync("Radzen.openPopup", target, GetId(), false, null, null, null, Reference, nameof(OnClose));
        }
        else
        {
            await CloseAsync();
        }
    }

    public async Task CloseAsync(ElementReference target)
    {
        open = false;
        this.target = target;

        await CloseAsync();
    }

    ElementReference target;

    [JSInvokable]
    public async Task OnClose()
    {
        open = false;

        await Close.InvokeAsync(null);
    }

    public async Task CloseAsync()
    {
        await JSRuntime.InvokeVoidAsync("Radzen.closePopup", GetId(), Reference, nameof(OnClose));
    }
}